<?php
class UserController extends Controller {
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			)
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$loginForm = new loginForm;
		$model = new SignupForm;
		$model->scenario = "insert";
		$this->validateAjax($model);
		if(isset($_POST['LoginBtn'])){
			$this->forward('login');
		}
		if(isset($_POST['SignupForm'])){
			$model->setAttributes($_POST['SignupForm'], false);

			if($model->validate()){
				$user = new User;
				$user->setAttributes($_POST['SignupForm'], false);
				$result_user = $user->upsert();
				if($result_user === true){
					$user_profile = new UserProfile;
					$user_profile->setAttributes($_POST['SignupForm'], false);
					$user_profile->user_id = $user->id;
					$result_profile = $user_profile->upsert();
					$this->redirect(array('user/signupSuccess/username/'.$user->username.'/email/'.$user->email));
				}
			}
		}
		$this->render('create',array(
			'model'=>$model,
			'loginForm'=>$loginForm,
		));
	}

	public function actionSignupSuccess(){
		$this->render("signup_success");
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('User');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return User the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=User::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	public function actionForgotPassword(){
		$model = new ForgotForm();
		$this->validateAjax($model);
		if(Yii::app()->request->isPostRequest && !empty($_POST['ForgotForm'])){
			$model->setAttributes($_POST['ForgotForm'], false);
			if($model->validate()){
				$user = User::model()->findByAttributes(array('email' => $model->email));
				if(is_object($user)){
					$user->reset_code = sha1($user->email.time());
					$result = $user->sendResetPassword();
					if($result){
						$this->redirect(array('user/notifyResetPassword/email/'.$user->email));
					}
				}
			}
		}
		$this->render("forgot_pass",array('model' => $model));
	}

	public function actionNotifyResetPassword(){
		$this->render("send_reset_success");
	}

	public function actionResetPassword(){
		$model = null;
		if(!empty($_GET['code']) && !empty($_GET['reset_code']) && is_string($_GET['reset_code']) && is_string($_GET['code'])){
			echo $_GET['reset_code'];die;
			$user = User::model()->findByAttributes(array('code' => $_GET['code'], 'reset_code' => $_GET['reset_code']));
			echo 1;die;
			if(is_object($user)){
				$model = new ResetPassForm();
				$this->validateAjax($model);
				if(Yii::app()->request->isPostRequest && !empty($_POST['ResetPassForm'])){
					$model->setAttributes($_POST['ResetPassForm'], false);
					if($model->validate()){
						$result = $user->resetPassword($model->password);
						if($result){
							$this->redirect(array('user/resetSuccess'));
						}
					}
				}
			}
		}
		$this->render('reset_password', array('model' => $model));
	}

	public function actionResetSuccess(){
		$this->render("reset_success");
	}

    public function actionLogin(){
		$model=new LoginForm;
		$service = Yii::app()->request->getQuery('service');
		if (isset($service)) {
			$authIdentity = Yii::app()->eauth->getIdentity($service);
			$authIdentity->redirectUrl = Yii::app()->user->returnUrl;
			$authIdentity->cancelUrl = $this->createAbsoluteUrl('user/login');

			if ($authIdentity->authenticate()) {
				$identity = new EAuthUserIdentity($authIdentity);

				// successful authentication
				if ($identity->authenticate()) {
					Yii::app()->user->login($identity);
					$user_login = User::model()->findByAttributes(array('open_id' => Yii::app()->user->getId()));
					if(!is_object($user_login)){
						$user_login = new User;
						$user_login->status = true;
						$user_login->createOpenUser(Yii::app()->user->getId(), Yii::app()->user->getName(), Yii::app()->user->getState('service'));
					}
					Yii::app()->user->setState('current_user', $user_login);
					// special redirect with closing popup window
					$authIdentity->redirect();
				}
				else {
					// close popup window and redirect to cancelUrl
					$authIdentity->cancel();
				}
			}

			// Something went wrong, redirect to login page
			$this->redirect(array('user/login'));
		}
		// collect user input data
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
			if($model->validate() && $model->login())
				$this->redirect(Yii::app()->createUrl('/'));
		}
    	$this->render('login', array('model' => $model));
    }

    public function actionLogout(){
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->createUrl('user/login'));
    }

    public function actionActive(){
    	if(empty($_GET['code']) || empty($_GET['active_code']) || !is_string($_GET['code']) || !is_string($_GET['active_code'])){
    		$this->redirect('activeError');
    	}
    	$user = User::model()->findByAttributes(array('code' => $_GET['code'], 'active_code' => $_GET['active_code']));
    	if(!is_object($user)){
    		$this->redirect(array('user/activeError'));
    	}
    	$user->status = true;
    	$user->active_code = null;
    	$user->active_time = date('Y-m-d H:i:s');
    	$user->update();
    	// Auto login after active
    	$identity=new UserIdentity($user->username,$user->password);
    	if($identity->authenticate(false)){
			Yii::app()->user->login($identity);
	    	Yii::app()->user->setState('current_user', $user);
    	}
    	$this->redirect('activeSuccessful');
    }

    public function actionActiveSuccessful(){
    	$this->render('active_success', array());
    }

    public function actionActiveError(){
    	$this->render('active_error');
    }

    public function actionTest()
    {
    	$link = 'www.gameoline.com/gamevl/user/active/code/40906834/active_code/$2a$13$J2/AMSX3hlYw8wEpMt770eQHCAE90k/B53rjTQPOn1WOykWrgxCvu';
    	$this->render('//mail/mailactive', array('link'=>$link, 'name'=>'pinpong'));
    }
}
